<template>
  <div class="page pettySavings-eidt">
    <StoreChoice
      ref="StoreChoice"
      :current="current"
      :multipleChoice="false"
      v-on:listenToStoreSelect="getSelectStoreValue"
      :hasTotal="false"
      reqUrl="/newapp/deposit/queryShopSelect.do"
    />
    <awesome-picker
      ref="pickerActivityType"
      colorTitle="#38ADFF"
      colorConfirm="#38ADFF"
      :textTitle="pickerActivityType.textTitle"
      :data="pickerActivityType.data"
      :anchor="pickerActivityType.anchor"
      @confirm="handlepickerActivityTypeConfirm"
      class="pickerZindex"
    ></awesome-picker>
    <div class="scroll-view">
      <customHeader :middleTitle="middleTitle"  @leftCallBack="goBack" />
      <div class="page-body">
        <div class="form-title">基础信息</div>
        <ul class="form-style">
          <li>
            <span>活动名称</span>
            <div>
              <inputClear
                placeholder="请填写"
                v-model.trim="activityName"
                warpClass="textright"
                :maxlength="20"
              ></inputClear>
            </div>
          </li>
          <li>
            <span>卡名称</span>
            <div>
              <inputClear
                placeholder="请填写"
                v-model.trim="couponName"
                warpClass="textright"
                :maxlength="20"
              ></inputClear>
            </div>
          </li>
          <li class="align-center">
            <span>LOGO</span>
            <div @click="uploadImg" class="alignCenter">
              <img v-if="couponLogo" class="logo" :src="previewUrl" alt />
              <span v-else>请选择</span>
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <template v-if="$route.query.type=='edit'">
            <li class="disabled">
              <span>卡类型</span>
              <div class="pick-value">
                {{pickerActivityType.selected.text}}
                <i class="zhk-list_rarrow"></i>
              </div>
            </li>
            <li class="disabled">
              <span>活动门店</span>
              <div v-if="pickerActivityType.selected.value==1">{{"全部门店"}}</div>
              <div v-else>
                {{shopName?shopName:"请选择"}}
                <i class="zhk-list_rarrow"></i>
              </div>
            </li>
          </template>
          <template v-else>
            <li @click="showPicker('pickerActivityType')">
              <span>卡类型</span>
              <div class="pick-value">
                {{pickerActivityType.selected.text}}
                <i class="zhk-list_rarrow"></i>
              </div>
            </li>
            <li>
              <span>活动门店</span>
              <div v-if="pickerActivityType.selected.value==1">{{"全部门店"}}</div>
              <div v-else @click="handleClickSelectStore">
                {{shopName?shopName:"请选择"}}
                <i class="zhk-list_rarrow"></i>
              </div>
            </li>
          </template>
        </ul>
        <div class="form-title">储值规则</div>
        <div class="czgz">
          <ul v-show="ruleList.length">
            <li v-for="(rule,index) in ruleList" :key="index">
              <span>
                充值
                <input type="number" v-model.trim.number="rule.rechargeAmt" placeholder="请填写" />元
              </span>
              <div class="split"></div>
              <span>
                赠送
                <input type="number" v-model.trim.number="rule.additionalAmt" placeholder="请填写" />元
              </span>
              <div class="del">
                <i class="zhk-list_sc" v-show="ruleList.length>1" @click="delRule(index)"></i>
              </div>
            </li>
          </ul>
          <div class="add-rule" @click="addRule" v-show="ruleList.length<12">
            <i class="zhk-nav_add"></i>增加
          </div>
        </div>
        <ul class="form-style">
          <li>
            <div class="flex-item-right">
              <div>
                订单金额高于
                <input
                  type="number"
                  placeholder="请填写"
                  v-model.number="recommendLimit"
                  style="text-align:center"
                />元，给顾客推荐储值
              </div>
              <div class="sub-text">当消费金额大于等于储值规则中的最高额度时，不展示储值活动</div>
            </div>
          </li>
          <li class="align-center" v-show="false">
            <span>使用余额时叠加津贴</span>
            <div>
              <mt-switch v-model="canOverlay"></mt-switch>
            </div>
          </li>
        </ul>
        <ul class="form-style">
          <li>
            <div class="flex-item-right">
              <div>备注</div>
              <textarea placeholder="非必填，仅内部可见（最多40个字）" v-model="couponDesc" maxlength="40"></textarea>
            </div>
          </li>
        </ul>
      </div>
      <div class="btn" @click="submit">提交</div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import searchBar from "../../components/searchBar/searchBar";
import inputClear from "../../components/inputClear/inputClear";
import noData from "../../components/noData/noData";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import jsBridge from "../../tools/jsBridge.js";
import moment from "moment";
import config from "../../base/profile/config.json";
import { Toast, Switch } from "mint-ui";
import AwesomePicker from "vue-awesome-picker";
Vue.use(AwesomePicker);
Vue.component(Switch.name, Switch);

export default {
  name: "pettySavingsEdit",
  data() {
    return {
      current: [],
      loadding: false,
      couponActivityId: "",
      middleTitle: "创建活动",
      pickerActivityType: {
        anchor: [],
        textTitle: "卡类型",
        selected: { text: "请选择", value: "" },
        data: [{ value: "通用", id: 1 }, { value: "单门店", id: 0 }]
      },
      ruleList: [{ rechargeAmt: "", additionalAmt: "" }],
      canOverlay: false,
      recommendLimit: "",
      couponLogo: config.pettySavingsDefaultLogo,
      shopId: "",
      shopName: "请选择",
      couponDesc: "",
      couponName: "储值卡",
      activityName: "会员储值" + moment().format("YYYY-MM-DD")
    };
  },
  methods: {
    goBack() {
      if (this.$refs.StoreChoice.popupVisible) {
        this.$refs.StoreChoice.back();
      }
      else {
        if (String(this.$route.query.close) == 'true') {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    //点击请选择弹出选择项
    showPicker(ref) {
      this.$refs[ref].show();
    },
    handleClickSelectStore() {
      this.$refs.StoreChoice.popupShow();
    },
    addRule() {
      this.ruleList.push({ rechargeAmt: "", additionalAmt: "" });
    },
    delRule(index) {
      this.ruleList.splice(index, 1);
    },
    handlepickerActivityTypeConfirm(v) {
      this.pickerActivityType.anchor = v;
      this.pickerActivityType.selected.value = this.pickerActivityType.data[v[0].index].id;
      this.pickerActivityType.selected.text = v[0].value;
      this.shopId = "";
      this.shopName = "";
    },
    getSelectStoreValue(value, shopName) {
      var shopId = value[0].selectKey;
      this.shopId = shopId;
      this.shopName = shopName;
    },
    uploadImg() {
      jsBridge.selectPicture(
        {
          options: "选择图片",
        },
        (result) => {
          this.doUploadPic(result);
        },
        (result) => {

        }
      );
    },
    doUploadPic(result) {
      const url = window.APP.serverUrl + "/app/img/uploadShopImg.do";
      jsBridge.uploadPic(
        {
          url: url,
          file: result.resultObject,
          data: {},
          crop: {},
          compress: { sizeLimit: "2", unit: "M" }
        },
        (result) => {
          //以下为正常的业务逻辑
          if (result && result.success) {
            const uploadResult = result.resultObject;
            if (uploadResult) {
              this.couponLogo = uploadResult.imageUrl;
              return;
            }
          }
          const msg = result.msg || "上传失败";
          Toast(msg);
        },
        (result) => {

        }
      );
    },
    getDetails() {
      this.ajax({
        type: "get",
        url: "/newapp/deposit/queryDepositCardActivityDetail.do?couponActivityId=" + this.couponActivityId,
        controlLoading: false
      })
        .then(res => {
          if (res.success && res.resultObject) {
            const data = res.resultObject;
            this.activityName = data.activityName;
            this.couponName = data.couponName;
            this.couponLogo = data.couponLogo;
            this.canOverlay = data.canOverlay === 0 ? true : false;
            this.recommendLimit = data.recommendLimit;
            let activityType = this.pickerActivityType.data.filter((item) => { return item.id == data.activityType });
            if (activityType.length > 0) {
              this.pickerActivityType.selected.value = activityType[0].id;
              this.pickerActivityType.selected.text = activityType[0].value;
              this.pickerActivityType.anchor = [{ index: data.activityType == 1 ? 0 : 1 }];
            }
            this.ruleList = data.ruleList;
            if (data.activityType === 0) {
              this.shopName = data.shopList[0].shopName;
              this.shopId = data.shopList[0].shopId;
              this.current = data.shopList.map((shop) => { return { selectKey: shop.shopId } });
            }
            this.couponDesc = data.couponDesc;
          } else {
            Toast(res.msg);
          }
        })
        .catch(err => {
        });
    },
    submit() {
      if (!this.activityName) {
        Toast("请填写活动名称");
        return;
      }
      if (!this.couponName) {
        Toast("请填写卡名称");
        return;
      }
      if (this.pickerActivityType.selected.value === "" || this.pickerActivityType.selected.value === null) {
        Toast("请选择卡类型");
        return;
      }
      if (this.pickerActivityType.selected.value == 0 && !this.shopId) {
        Toast("请选择活动门店");
        return;
      }
      let isREmpty = false;
      let isAEmpty = false;
      let isillegal = false;

      this.ruleList.forEach((e) => {
        if (e.rechargeAmt == "") {
          isREmpty = true;
          return;
        }
        if (e.additionalAmt == "") {
          isAEmpty = true;
          return;
        }
        if ((!(/^\+?[1-9]\d*$/.test(e.rechargeAmt))) || e.rechargeAmt > 99999) {
          isillegal = true;
          return;
        }
        if ((!(/^\+?[1-9]\d*$/.test(e.additionalAmt))) || e.additionalAmt > 99999) {
          isillegal = true;
          return;
        }

      });
      if (isREmpty) {
        Toast("请填写充值金额");
        return;
      }
      if (isAEmpty) {
        Toast("请填写赠送金额");
        return;
      }
      if (isillegal&&!config.CZdebugger) {
        Toast("金额请填写的1~99999的整数");
        return;
      }
      if (CommonUtil.repeatInArray(this.ruleList, "rechargeAmt")) {
        Toast("充值金额不允许重复");
        return;
      }
      if (!this.recommendLimit) {
        Toast("请填写消费金额限制");
        return;
      }

      let ruleList = JSON.parse(JSON.stringify(this.ruleList));
      ruleList = ruleList.sort((a, b) => {
        return b["rechargeAmt"] - a["rechargeAmt"];
      });
      if (ruleList[0].rechargeAmt < this.recommendLimit) {
        Toast("消费金额限制<" + ruleList[0].rechargeAmt + "元");
        return;
      }
      this.loadding = true;
      const url = this.couponActivityId ? "/newapp/deposit/updateDepositCardActivity.do" : "/newapp/deposit/createDepositCardActivity.do";
      let param = {
        activityName: this.activityName,
        couponName: this.couponName,
        couponLogo: this.couponLogo,
        canOverlay: this.canOverlay ? 0 : 1,
        recommendLimit: this.recommendLimit,
        activityType: this.pickerActivityType.selected.value,
        ruleList: this.ruleList,
        shopList: this.pickerActivityType.selected.value === 0 ? [{ shopName: this.shopName, shopId: this.shopId }] : null,
        couponDesc: this.couponDesc,
      };
      if (this.couponActivityId) {
        param.couponActivityId = this.couponActivityId;
      }
      this.ajax({
        type: "post",
        data: param,
        url: url,
        controlLoading: true
      })
        .then(res => {
          if (res.success && res.resultObject) {
            Toast("操作成功");
            this.$router.push("/pettySavings");
          } else {
            this.loadding = false;
            Toast(res.msg);
          }
        })
        .catch(err => {
          this.loadding = false;
        });
    }
  },
  computed: {
    previewUrl() {
      return config.previewUrlPrefix + this.couponLogo;
    }
  },
  created() {
    this.couponActivityId = this.$route.query.couponActivityId;
    if (this.$route.query.type=="edit") {
      this.middleTitle = "编辑活动";
      this.getDetails();
    }
  },
  components: {
    customHeader,
    inputClear,
    StoreChoice
  }
};
</script>
<style lang='scss' scoped>
@import "pettySavings";
</style>
<style lang='scss'>
.textright {
  text-align: right !important;
}
</style>
